(function($) {
	
	function buildForm(target){
		var opts = $.data(target, 'flexform').options;
		$(target).form($.extend({}, opts));
		
		$(target).css({"display":"flex", "flex-wrap":"wrap","align-items":"center"});

		var labelWidth = opts.labelWidth;
		var labelAlign = opts.labelAlign;
		if(!labelAlign){
			labelAlign = "right"
		}
		if(!labelWidth){
			labelWidth = 0;
		}
		$(target).find("div > label").each(function(){
			var width = $(this).css("width");
			width =  Number(width.replace("px",""));
			if(width>labelWidth) labelWidth = width;
		});
		labelWidth = labelWidth+5;
		$(target).find("div > label").css({
				"flex-shrink":"0",
				"width": labelWidth+"px",
				"text-align":labelAlign
			});

		var cellWidth = opts.cellWidth;
		if(!cellWidth){
			cellWidth = 220;
		}
		$(target).children("div").each(function(){
			var colspan = $(this).attr("colspan");
			var cellMargin = opts.cellMargin;
			if (!colspan) {
				colspan = 1;
			}
			if(!cellMargin){
				cellMargin = 0;
			}
			var cellStyle = {"overflow":"hidden", "display":"inline-flex", "flex-wrap":"nowrap","align-items":"center", "margin":cellMargin+"px"};
			var thisCellWidth = cellWidth*colspan + (colspan-1)*cellMargin*2;
			cellStyle.width= thisCellWidth+"px";
			var oneline = $(this).attr("oneline");
			if(oneline) cellStyle.width= "100%";
			$(this).css(cellStyle);
		});
		
		$(target).children("div").each(function(){
			$(this).children("div").each(function() {
				$(this).css({"flex":"auto", "overflow":"hidden"});
				if($(this).children("span").length>0){
					$(this).children("input").textbox("resize","100%");
				} else {
					$(this).children("input").css("width","100%");
				}
			});
		});
	}
	
	/**
	 * 插件定义
	 */
	$.fn.flexform = function(options, param) {
		if (typeof options == 'string'){
			var method = $.fn.flexform.methods[options];
			if (method){
				return method(this, param);
			} else {
				return this.form(options, param);
			}
		}

		options = options || {};
		return this.each(function(){
			var state = $.data(this, 'flexform');
			if (state){
				$.extend(state.options, options);
			} else {
				$.data(this, 'flexform', {
					options: $.extend({}, $.fn.flexform.defaults, $.fn.flexform.parseOptions(this), options)
				});
			}
			buildForm(this);
		});
		
	};

	/**
	 * 默认值配置
	 */
	$.fn.flexform.defaults = {
	};
	
	/**
	 * 对外暴露的方法
	 */
	$.fn.flexform.methods = {
	};

	/**
	 * class声明式定义属性data-options转化为options
	 * @param {Object} target DOM对象
	 * @return {TypeName} 
	 */
	$.fn.flexform.parseOptions = function(target){
		return $.extend({}, $.fn.form.parseOptions(target), {});
	};


	$.parser.plugins.push('flexform'); //将自定义的插件加入 easyui 的插件组

})(jQuery);